package com.jiyinit.web.core.video.controller;

import com.jiyinit.core.framework.base.util.Check;
import com.jiyinit.web.core.business.enums.OperationTypeConstant;
import com.jiyinit.web.core.common.util.MessagePush;
import com.jiyinit.web.core.video.dto.SRSRequest;
import com.jiyinit.web.core.video.dto.SRSResponse;
import com.jiyinit.web.core.video.entity.TabCoreVideoEntity;
import com.jiyinit.web.core.video.service.VideoServiceImpl;
import com.jiyinit.web.core.video.service.VideoUserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * Created by user1 on 2019/1/14.
 * <p>
 *    •	返回值：SRS要求HTTP服务器返回HTTP200并且response内容为整数错误码（0表示成功），其他错误码会断开客户端连接。
 * </p>
 */
@Controller
@RequestMapping(value = "/srs")
public class SRSController implements SRSInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(SRSController.class);

    @Resource(name = "core.videoServiceImpl")
    private VideoServiceImpl videoService;

    @Resource(name = "core.videoUserServiceImpl")
    private VideoUserServiceImpl videoUserService;


    /**
     * 监听srs用户连接
     * @param srsRequest
     * @param request
     * @param response
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/onConnect")
    public void onConnect(@RequestBody SRSRequest srsRequest, HttpServletRequest request, HttpServletResponse response) {
        String jsonStr = srsRequest.toString();
        LOGGER.info("onConnect 传入参数: {}", jsonStr);

        response.setStatus(HttpStatus.OK.value());
        try {
            response.getWriter().print(SRSResponse.success);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 监听关闭
     * @param srsRequest
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/onClose")
    public void onClose(@RequestBody SRSRequest srsRequest, HttpServletRequest request, HttpServletResponse response) {
        LOGGER.info("onClose 请求参数为: {}", srsRequest.toJsonStr());
        response.setStatus(HttpStatus.OK.value());
        try {

            response.getWriter().print(SRSResponse.success);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 监听直播流发布
     * @param srsRequest
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/onPublish")
    public void onPublish(@RequestBody SRSRequest srsRequest, HttpServletRequest request, HttpServletResponse response) {
        LOGGER.info("onPublish 请求参数为: {}", srsRequest.toJsonStr());

        TabCoreVideoEntity videoRequest = new TabCoreVideoEntity();
        videoRequest.setViHomeId(srsRequest.getStream());
        TabCoreVideoEntity entity = videoService.findOneBySelective(videoRequest);
        if(!Check.isNullObj(entity)){
            TabCoreVideoEntity videoEntity = entity;
            LOGGER.info(videoEntity.toString());
            String participantIds = videoEntity.getParticipantIds();
            LOGGER.info("participantIds is :{}", participantIds);

            if(!Check.isNullStrStrict(participantIds)){
                String[] userIds = participantIds.split(",");
                pushMsg(videoEntity.getSponsorId(), userIds, "发布直播流", "1");
            }
        }
        response.setStatus(HttpStatus.OK.value());
        try {
            response.getWriter().print(SRSResponse.success);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 监听直播流关闭
     * @param srsRequest
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/onUnpublish")
    public void onUnpublish(@RequestBody SRSRequest srsRequest, HttpServletRequest request, HttpServletResponse response) {
        LOGGER.info("onUnpublish 请求参数为: {}", srsRequest.toString());

        TabCoreVideoEntity videoRequest = new TabCoreVideoEntity();
        videoRequest.setViHomeId(srsRequest.getStream());
        TabCoreVideoEntity entity = videoService.findOneBySelective(videoRequest);
        if(!Check.isNullObj(entity)){
            TabCoreVideoEntity videoEntity = entity;
            LOGGER.info(videoEntity.toString());
            String participantIds = videoEntity.getParticipantIds();
            LOGGER.info("participantIds is :{}", participantIds);

            if(!Check.isNullStrStrict(participantIds)){
                String[] userIds = participantIds.split(",");
                String isClose = entity.getIsClose();
                if(isClose.equals("1")){//1的话为主动关闭
                    pushMsg(videoEntity.getSponsorId(), userIds, "该视频会议已结束", "2");
                }else if(isClose.equals("0")){
                    pushMsg(videoEntity.getSponsorId(), userIds, "该视频会议暂时中断, 请稍后...", "3");
                }
            }
        }
        response.setStatus(HttpStatus.OK.value());
        try {
            response.getWriter().print(SRSResponse.success);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 监听用户播放
     * @param srsRequest
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/onPlay")
    public void onPlay(@RequestBody SRSRequest srsRequest, HttpServletRequest request, HttpServletResponse response) {
        LOGGER.info("onPlay 请求参数为: {}", srsRequest.toJsonStr());
        response.setStatus(HttpStatus.OK.value());
        try {
            response.getWriter().print(SRSResponse.success);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 监听用户暂停播放
     * @param srsRequest
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/onStop")
    public void onStop(@RequestBody SRSRequest srsRequest, HttpServletRequest request, HttpServletResponse response) {
        LOGGER.info("onStop 请求参数为: {}", srsRequest.toJsonStr());
        response.setStatus(HttpStatus.OK.value());
        try {
            response.getWriter().print(SRSResponse.success);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 视频录制完毕时
     * @param srsRequest
     * @param request
     * @param response
     */
    @Override
    @ResponseBody
    @RequestMapping(value = "/onDvr")
    public void onDvr(@RequestBody SRSRequest srsRequest, HttpServletRequest request, HttpServletResponse response) {
        LOGGER.info("onDvr 请求参数为: {}", srsRequest.toJsonStr());
        response.setStatus(HttpStatus.OK.value());
        try {
            response.getWriter().print(SRSResponse.success);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @param userId
     * @param sendUser
     */
    public void pushMsg(String userId, String[] sendUser, String msg, String title){
        //极光推送
        Map<String, String> returnStr = new HashMap<>();
        //returnStr.put("taskId",String.valueOf(task.getTaskId()));
        returnStr.put("title", title);
        returnStr.put("userId", userId);
        //returnStr.put("createUid",String.valueOf(task.getCreateUid()));
        //returnStr.put("toUserId", sendUser[0]);
        returnStr.put("type", OperationTypeConstant.VIDEO_PUSH);
        returnStr.put("content",  msg);
        String[] sendUsers = sendUser;
        new MessagePush(returnStr,sendUsers);
    }

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }


    @RequestMapping(value = "/test")
    public String test(HttpServletRequest request, HttpServletResponse response) {
        String ipAddress = getIpAddress(request);
        System.out.println(ipAddress);
        return "video";
    }

    @RequestMapping(value = "/getFlv")
    public void getFlv(HttpServletRequest request, HttpServletResponse response){
        String path = "C:\\Users\\user1\\Desktop\\4146_20190123_141438_34fa.flv";
        File file = new File(path);
        try {
            FileInputStream fis = new FileInputStream(file);
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("video/flv");
            byte[] bytes = new byte[1024];
            while (fis.read(bytes) != -1){
                out.write(bytes);
            }
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/notice")
    public String tonoticeDetail(){
        return "notice/noticeDetail";
    }
}
